package com.zhq.blog.manage.domain.fronted.controller;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.AbstractPageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.zhq.blog.core.domain.game.Game;
import com.zhq.blog.core.domain.game.GamePeriod;
import com.zhq.blog.core.domain.game.GamePeriod.GamePeriodState;
import com.zhq.blog.core.domain.game.support.AutoBet;
import com.zhq.blog.core.domain.game.support.AutoBetBase.AutoBetType;
import com.zhq.blog.core.domain.game.support.AutoBetBase.RunningState;
import com.zhq.blog.core.domain.game.support.AutoBetDetail;
import com.zhq.blog.core.domain.game.support.Cathectic;
import com.zhq.blog.core.domain.game.support.Cathectic.MunualOrAuto;
import com.zhq.blog.core.domain.game.support.CathecticModel;
import com.zhq.blog.core.domain.game.support.CathecticModelDetail;
import com.zhq.blog.core.domain.game.support.Odds;
import com.zhq.blog.core.domain.game.support.PermutationBet;
import com.zhq.blog.core.domain.game.support.PermutationBetDetail;
import com.zhq.blog.core.domain.other.DetailsOfFunds;
import com.zhq.blog.core.domain.other.DetailsOfFunds.DetailType;
import com.zhq.blog.core.domain.user.User;
import com.zhq.blog.manage.domain.fronted.controller.support.UserInterceptor;

/**
 * @title:GameController.java
 * @package com.zhq.blog.manage.domain.fronted.controller
 * @author 张恒强
 * @date 2015年1月7日 下午3:17:39
 * @version V1.0
 */
@Controller
@RequestMapping("/fgame/*")
public class GameController extends BaseController{
	
	
	@RequestMapping("{id}/index")
	public MallModelView index(HttpServletRequest request,@PathVariable long id,
			@PageableDefault(page=0,size=40) Pageable pageable){
		Page<GamePeriod> periods = context.getGamePeriodRepository().find_all_by_gameId(id,pageable);
		
		GamePeriod period = context.getGamePeriodRepository()
				.find_to_be_lottery_by_gameId_state(id).get(0);
		
		
		//设置盈利 胜率 期数  设置每一期玩家的投注及中奖金币
		long gain = 0,total_participate = 0;
		double winning = 0;
		if(request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)!= null){
			User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
			
			if(periods.getTotalElements()>0){
				for (GamePeriod gamePeriod : periods) {
					Long sum = context.getCathecticRepository()
							.sum_by_game_period_user(id, user.getId(), gamePeriod.getPeriod());
					Long sum_winning = context.getCathecticRepository()
							.sum_winning_by_game_period_user(id, user.getId(), gamePeriod.getPeriod());
					if (sum != null) {
						gamePeriod.setSingleUserBetMoney(sum);
					}
					if(sum_winning != null){
						gamePeriod.setSingleUserWinMoney(sum_winning);
					}
				}
			}
			
			Calendar c = Calendar.getInstance();
			c.set(Calendar.HOUR_OF_DAY, 0);
			c.set(Calendar.MINUTE, 0);
			c.set(Calendar.SECOND, 0);
			Long gain_temp = context.getCathecticRepository()
					.gain_today_by_gameId_userId_lottered(id, user.getId(), c.getTime());
			
			
			if(gain_temp != null){
				gain = gain_temp;
				total_participate = context.getCathecticRepository()
						.numbers_today_by_gameId_userId_lottered(id,user.getId(),c.getTime());
				Long winner_participate =context.getCathecticRepository()
						.winner_numbers_by_gameId_userId_lottered_winning(id, user.getId(), c.getTime());
				if (winner_participate != null) {
					winning = Double.parseDouble(winner_participate+"")/total_participate*100;
				}
			}
		}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return buildModelView("/game/index", request).add("periods",periods)
				.add("gain",gain).add("total_participate", total_participate).
				add("winning", winning).add("to_be_lottery",period.getPeriod())
				.add("to_be_lottery_time", df.format(period.getLotteryTime()))
				.add("serverTime",df.format(new Date()));
	}
	
	@RequestMapping("{id}/cathecticmodel")
	public MallModelView cathecticmodel(HttpServletRequest request,@PathVariable long id,
			@PageableDefault(page=0,size=20) Pageable pageable){
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		Page<CathecticModel> models = context.getCathecticModelRepository().find_all_by_game_user(id,user.getId(), pageable);
		return buildModelView("/game/catheticmodel", request).add("models", models);
	}
	
	@RequestMapping("{id}/addmodel")
	public MallModelView addmodel(HttpServletRequest request,@PathVariable long id){
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		List<Odds> odds = context.getOddsRepository().find_all_by_game(id);
		List<CathecticModelDetail> details = new ArrayList<CathecticModelDetail>();
		for(Odds odd:odds){
			CathecticModelDetail detail = new CathecticModelDetail();
			detail.setBetNumber(odd.getNumber());
			detail.setStandardRate(odd.getStandard());
			details.add(detail);
		}
		return buildModelView("/game/addmodel", request)
				.add("details", details)
				.add("models", context.getCathecticModelRepository().find_all_by_game_user(id, user.getId()));
		
	}
	@RequestMapping(value="{id}/savemodel",method = RequestMethod.POST)
	public MallModelView savemodel(HttpServletRequest request,
			String model_json,String detail_json,@PathVariable long id,long model_id){
		try {
			CathecticModel model = null;
			if(model_id == 0){
				model = (CathecticModel) JSONObject.toBean(JSONObject.fromObject(model_json), CathecticModel.class);
			}else{
				model = context.getCathecticModelRepository().findOne(model_id);
				context.getCathecticModelDetailRepository().delete(context.getCathecticModelDetailRepository().find_by_modelId(model_id));
			}
			User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
			model.setGameId(id);
			model.setUserId(user.getId());
			model = context.getCathecticModelRepository().save(model);
			JSONArray jsonArray = JSONArray.fromObject(detail_json);
			long num = 0;
			for (int i = 0; i < jsonArray.size(); i++) {
				CathecticModelDetail detail = (CathecticModelDetail) JSONObject.toBean(JSONObject.fromObject(jsonArray.get(i)),CathecticModelDetail.class);
				detail.setModelId(model.getId());
				num += detail.getBetMoney();
				context.getCathecticModelDetailRepository().save(detail);
			}
			model.setTotalBetMoney(num);
		} catch (Exception e) {
			logger.equals(e.getMessage());
			logger.equals(e.getStackTrace());
			return buildModelView("redirect:/fgame/"+id+"/cathecticmodel", request);
		}
		return buildModelView("redirect:/fgame/"+id+"/cathecticmodel", request);
	}
	
	@RequestMapping("{id}/editmodel")
	public MallModelView editmodel(HttpServletRequest request,long modelId,@PathVariable long id){
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		List<Odds> odds = context.getOddsRepository().find_all_by_game(id);
		List<CathecticModelDetail> details = context.getCathecticModelDetailRepository().find_by_modelId(modelId);
		for(Odds odd:odds){
			boolean flag = true;
			for(CathecticModelDetail detail:details){
				if(detail.getBetNumber() == odd.getNumber()){
					detail.setStandardRate(odd.getStandard());
					flag =false;
				}
			}
			if (flag) {
				CathecticModelDetail detail = new CathecticModelDetail();
				detail.setBetNumber(odd.getNumber());
				detail.setStandardRate(odd.getStandard());
				details.add(detail);
			}
		}
		Collections.sort(details, new Comparator<CathecticModelDetail>() {

			@Override
			public int compare(CathecticModelDetail o1, CathecticModelDetail o2) {
				return o1.getBetNumber()-o2.getBetNumber();
			}
		});
		return buildModelView("/game/addmodel", request)
				.add("details", details)
				.add("models", context.getCathecticModelRepository().find_all_by_game_user(id, user.getId()))
				.add("model", context.getCathecticModelRepository().findOne(modelId));
	}
	
	@RequestMapping("{id}/deletemodel")
	public ModelAndView deletemodel(HttpServletRequest request,long modelId,@PathVariable long id){
		
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		
		//删除所有的自动投注
		List<AutoBet> autoBets = context.getAutoBetRepository().find_by_game_user(id, user.getId());
		if (CollectionUtils.isNotEmpty(autoBets)) {
			for (AutoBet autoBet : autoBets) {
				autoBet.setDeleted(true);
				autoBet.setState(RunningState.STOPED);
				List<AutoBetDetail> details = context.getAutoBetDetailRepository()
						.find_by_autobetId(autoBet.getId());
				if (CollectionUtils.isNotEmpty(details)) {
					for (AutoBetDetail autoBetDetail : details) {
						autoBetDetail.setDeleted(true);
					}
				}
			}
		}
		//删除所有的智能投注
		List<Long> idsList = context.getPermutationBetDetailRepository()
				.find_by_modelId(modelId);
		if (CollectionUtils.isNotEmpty(idsList)) {
			for (Long long1 : idsList) {
				PermutationBet pBet = context.getPermutationBetRepository()
						.findOne(long1);
				pBet.setDeleted(true);
				pBet.setState(RunningState.STOPED);
				List<PermutationBetDetail> details = 
						context.getPermutationBetDetailRepository()
						.find_by_permutation(long1);
				if (CollectionUtils.isNotEmpty(details)) {
					for (PermutationBetDetail permutationBetDetail : details) {
						permutationBetDetail.setDeleted(true);
					}
				}
			}
		}
		
		//删除投注模式
		CathecticModel model = context.getCathecticModelRepository().findOne(modelId);
		List<CathecticModelDetail> details = context.getCathecticModelDetailRepository()
				.find_by_modelId(modelId);
		if (CollectionUtils.isNotEmpty(details)) {
			for (CathecticModelDetail cathecticModelDetail : details) {
				cathecticModelDetail.setDeleted(true);
			}
		}
		model.setDeleted(true);
		return buildModelView("redirect:/fgame/"+id+"/cathecticmodel", request);
	}
	
	@RequestMapping("{id}/auto")
	public MallModelView autoBetIndex(HttpServletRequest request,@PathVariable long id,
			String autoId){
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		List<AutoBet> autoBets = context.getAutoBetRepository().find_by_game_user(id, user.getId());
		List<CathecticModel> models = context.getCathecticModelRepository()
				.find_all_by_game_user(id, user.getId());
		if (CollectionUtils.isEmpty(models)) {
			logger.info("没有投注模式,跳转至投注模式列表界面！！");
			return buildModelView("redirect:/fgame/"+id+"/cathecticmodel", request);
		}
		
		AutoBet autoBet = null;
		List<AutoBetDetail> details = null;
		if (autoId != null) {
			autoBet = context.getAutoBetRepository().findOne(Long.parseLong(autoId));
			details = context.getAutoBetDetailRepository().find_by_autobetId(Long.parseLong(autoId));
		}else{
			autoBet = new AutoBet();
			autoBet.setStartBetPeriod(context.getGamePeriodRepository()
					.find_to_be_lottery_by_gameId_state(id).get(0).getPeriod());
			autoBet.setExecutePeriod(1000000);
			autoBet.setSuperLimit(1000000000);
			autoBet.setLowerLimit(0);
		}
		
		return buildModelView("/game/autobet", request)
				.add("autoBets", autoBets)
				.add("models", models)
				.add("autoBet", autoBet)
				.add("details", details);
	}
	
	
	
	@RequestMapping(value="{gid}/saveAuto",method=RequestMethod.POST)
	public MallModelView addAutoBet(HttpServletRequest request,@PathVariable long gid,
			AutoBet autoBet,String detail){
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		AutoBet bet = null;
		if (autoBet.getId() == null) {//新增
			bet = autoBet;
			bet.setState(RunningState.STOPED);
			bet.setGameId(gid);
			bet.setUserId(user.getId());
		}else{
			bet = context.getAutoBetRepository().findOne(autoBet.getId());
			bet.setName(autoBet.getName());
			bet.setStartBetPeriod(autoBet.getStartBetPeriod());
			bet.setExecutePeriod(autoBet.getExecutePeriod());
			bet.setSuperLimit(autoBet.getSuperLimit());
			bet.setLowerLimit(autoBet.getLowerLimit());
			bet.setStartModelId(autoBet.getStartModelId());
			
			List<AutoBetDetail> details = context.getAutoBetDetailRepository().find_by_autobetId(bet.getId());
			if (CollectionUtils.isNotEmpty(details)) {
				for (AutoBetDetail autoBetDetail : details) {
					autoBetDetail.setDeleted(true);
				}
			}
		}
		
		context.getAutoBetRepository().save(bet);
		
		JSONArray array = JSONArray.fromObject(detail);
		if (array.size()>0) {
			for (Object object : array) {
				AutoBetDetail detail2 = (AutoBetDetail) JSONObject.toBean(JSONObject.fromObject(object),AutoBetDetail.class);
				detail2.setAutoBetId(bet.getId());
				context.getAutoBetDetailRepository().save(detail2);
			}
		}
		return buildModelView("redirect:/fgame/"+gid+"/auto", request);
	}
	
	/**
	 * 改变自动投注的状态
	 * 停止  从头运行  继续运行  删除
	 * @param request
	 * @param id
	 * @param autoId
	 * @return
	 */
	@RequestMapping({"{id}/stopautobet","{id}/fromheadautobet","{id}/keepgoautobet","{id}/deleteautobet"})
	public MallModelView changeAutoBetState(HttpServletRequest request,@PathVariable long id,long autoId){
		String uri = request.getRequestURI();
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		AutoBet autoBet = context.getAutoBetRepository().findOne(autoId);
		if (uri.endsWith("stopautobet")) {
			autoBet.setState(RunningState.STOPED);
		}else if (uri.endsWith("fromheadautobet")) {
			List<AutoBet> autoBets = context.getAutoBetRepository().find_by_game_user(id, user.getId());
			if (CollectionUtils.isNotEmpty(autoBets)) {
				for (AutoBet autoBet2 : autoBets) {
					if (autoBet2.getId() != autoBet.getId()) {
						autoBet2.setState(RunningState.STOPED);
					}
				}
			}
			List<PermutationBet> permutationBets = context.getPermutationBetRepository()
					.find_by_game_user(id, user.getId());
			if(CollectionUtils.isNotEmpty(permutationBets)){
				for (PermutationBet permutationBet : permutationBets) {
					permutationBet.setState(RunningState.STOPED);
				}
			}
			autoBet.setFromHead(true);
			autoBet.setCurrentModelId(autoBet.getStartModelId());
			autoBet.setState(RunningState.RUNNING);
		}else if (uri.endsWith("keepgoautobet")) {
			List<AutoBet> autoBets = context.getAutoBetRepository().find_by_game_user(id, user.getId());
			if (CollectionUtils.isNotEmpty(autoBets)) {
				for (AutoBet autoBet2 : autoBets) {
					if (autoBet2.getId() != autoBet.getId()) {
						autoBet2.setState(RunningState.STOPED);
					}
				}
			}
			List<PermutationBet> permutationBets = context.getPermutationBetRepository()
					.find_by_game_user(id, user.getId());
			if(CollectionUtils.isNotEmpty(permutationBets)){
				for (PermutationBet permutationBet : permutationBets) {
					permutationBet.setState(RunningState.STOPED);
				}
			}
			autoBet.setState(RunningState.RUNNING);
		}else if (uri.endsWith("deleteautobet")) {
			autoBet.setState(RunningState.STOPED);
			autoBet.setDeleted(true);
			List<AutoBetDetail> details = context.getAutoBetDetailRepository().find_by_autobetId(autoId);
			if(CollectionUtils.isNotEmpty(details)){
				for (AutoBetDetail autoBetDetail : details) {
					autoBetDetail.setDeleted(true);
				}
			}
		}
		return buildModelView("redirect:/fgame/"+id+"/auto",request);
	}
	@RequestMapping("{id}/permutation")
	public MallModelView permutation(HttpServletRequest request,@PathVariable long id,
			String permutationId){
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		List<PermutationBet> permutationBets = context.getPermutationBetRepository()
				.find_by_game_user(id, user.getId());
		List<CathecticModel> models = context.getCathecticModelRepository()
				.find_all_by_game_user(id, user.getId());
		if (CollectionUtils.isEmpty(models)) {
			logger.info("没有投注模式,跳转至投注模式列表界面！！");
			return buildModelView("redirect:/fgame/"+id+"/cathecticmodel", request);
		}
		PermutationBet permutationBet = null;
		List<PermutationBetDetail> details = null;
		List<Integer> numbers = context.getGameRepository().findOne(id).getResultNumberList();
		if (permutationId != null) {
			permutationBet =context.getPermutationBetRepository()
					.findOne(Long.parseLong(permutationId));
			details = context.getPermutationBetDetailRepository()
					.find_by_permutation(Long.parseLong(permutationId));
			if(CollectionUtils.isNotEmpty(details)){
				for (Integer integer : numbers) {
					boolean flag = true;
					for (PermutationBetDetail detail :details) {
						if(detail.getBetNumber() == integer){
							flag = false;
							break;
						}
					}
					if(flag){
						details.add(new PermutationBetDetail(integer));
					}
				}
				Collections.sort(details, new Comparator<PermutationBetDetail>() {
					@Override
					public int compare(PermutationBetDetail o1,
							PermutationBetDetail o2) {
						return o1.getBetNumber()-o2.getBetNumber();
					}
				});
			}else{
				details = new ArrayList<PermutationBetDetail>();
				for (Integer integer : numbers) {
					details.add(new PermutationBetDetail(integer));
				}
			}
		}else{
			permutationBet = new PermutationBet();
			permutationBet.setStartBetPeriod(context.getGamePeriodRepository()
					.find_to_be_lottery_by_gameId_state(id).get(0).getPeriod());
			permutationBet.setExecutePeriod(1000000);
			permutationBet.setSuperLimit(1000000000);
			permutationBet.setLowerLimit(0);
			details = new ArrayList<PermutationBetDetail>();
			for (Integer integer : numbers) {
				details.add(new PermutationBetDetail(integer));
			}
		}
		return buildModelView("/game/permutationbet", request)
				.add("permutationBets", permutationBets)
				.add("models", models)
				.add("permutationBet", permutationBet)
				.add("details", details);
	}
	
	@RequestMapping(value="{gid}/savePermutation",method=RequestMethod.POST)
	public MallModelView addpermutationBet(HttpServletRequest request,@PathVariable long gid,
			PermutationBet permutationBet,String detail){
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		
		PermutationBet bet = null;
		if (permutationBet.getId() == null) {//新增
			bet = permutationBet;
			bet.setState(RunningState.STOPED);
			bet.setGameId(gid);
			bet.setUserId(user.getId());
		}else{
			bet = context.getPermutationBetRepository().findOne(permutationBet.getId());
			bet.setName(permutationBet.getName());
			bet.setStartBetPeriod(permutationBet.getStartBetPeriod());
			bet.setExecutePeriod(permutationBet.getExecutePeriod());
			bet.setSuperLimit(permutationBet.getSuperLimit());
			bet.setLowerLimit(permutationBet.getLowerLimit());
			
			List<PermutationBetDetail> details = context.getPermutationBetDetailRepository()
					.find_by_permutation(bet.getId());
			if (CollectionUtils.isNotEmpty(details)) {
				for (PermutationBetDetail permutationBetDetail : details) {
					permutationBetDetail.setDeleted(true);
				}
			}
		}
		
		context.getPermutationBetRepository().save(bet);
		
		JSONArray array = JSONArray.fromObject(detail);
		if (array.size()>0) {
			for (Object object : array) {
				PermutationBetDetail detail2 = (PermutationBetDetail) JSONObject.toBean(JSONObject.fromObject(object),PermutationBetDetail.class);
				detail2.setPermutationBetId(bet.getId());
				context.getPermutationBetDetailRepository().save(detail2);
			}
		}
		
		return buildModelView("redirect:/fgame/"+gid+"/permutation", request);
	}
	
	/**
	 * 改变自动投注的状态
	 * 停止  从头运行  继续运行  删除
	 * @param request
	 * @param id
	 * @param autoId
	 * @return
	 */
	@RequestMapping({"{id}/stoppermutationbet","{id}/fromheadpermutationbet","{id}/keepgopermutationbet","{id}/deletepermutationbet"})
	public MallModelView changePermutationBetState(HttpServletRequest request,@PathVariable long id,long permutationId){
		String uri = request.getRequestURI();
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		PermutationBet permutationBet = context.getPermutationBetRepository().findOne(permutationId);
		if (uri.endsWith("stoppermutationbet")) {
			permutationBet.setState(RunningState.STOPED);
		}else if (uri.endsWith("fromheadpermutationbet")) {
			List<AutoBet> autoBets = context.getAutoBetRepository().find_by_game_user(id, user.getId());
			if (CollectionUtils.isNotEmpty(autoBets)) {
				for (AutoBet autoBet2 : autoBets) {
					autoBet2.setState(RunningState.STOPED);
				}
			}
			List<PermutationBet> permutationBets = context.getPermutationBetRepository()
					.find_by_game_user(id, user.getId());
			if(CollectionUtils.isNotEmpty(permutationBets)){
				for (PermutationBet permutationBet2 : permutationBets) {
					if(permutationBet2.getId() != permutationBet.getId())
					permutationBet2.setState(RunningState.STOPED);
				}
			}
			permutationBet.setFromHead(true);
			permutationBet.setState(RunningState.RUNNING);
		}else if (uri.endsWith("keepgopermutationbet")) {
			List<AutoBet> autoBets = context.getAutoBetRepository().find_by_game_user(id, user.getId());
			if (CollectionUtils.isNotEmpty(autoBets)) {
				for (AutoBet autoBet2 : autoBets) {
						autoBet2.setState(RunningState.STOPED);
				}
			}
			List<PermutationBet> permutationBets = context.getPermutationBetRepository()
					.find_by_game_user(id, user.getId());
			if(CollectionUtils.isNotEmpty(permutationBets)){
				for (PermutationBet permutationBet2 : permutationBets) {
					if(permutationBet2.getId() != permutationBet.getId()){
						permutationBet2.setState(RunningState.STOPED);
					}
				}
			}
			permutationBet.setState(RunningState.RUNNING);
		}else if (uri.endsWith("deletepermutationbet")) {
			permutationBet.setState(RunningState.STOPED);
			permutationBet.setDeleted(true);
			List<PermutationBetDetail> details = context.getPermutationBetDetailRepository().find_by_permutation(permutationId);
			if(CollectionUtils.isNotEmpty(details)){
				for (PermutationBetDetail permutationBetDetail : details) {
					permutationBetDetail.setDeleted(true);
				}
			}
		}
		return buildModelView("redirect:/fgame/"+id+"/permutation",request);
	}
	
	@RequestMapping("{id}/help")
	public MallModelView help(HttpServletRequest request,@PathVariable long id){
		
		return buildModelView("/game/help", request);
	}
	
	/**
	 * 手工投注
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("{id}/mannualBet")
	public MallModelView mannualBet(HttpServletRequest request,@PathVariable long id,
			long period,String modelId){
		GamePeriod gp = context.getGamePeriodRepository().find_by_gameId_and_period(id, period).get(0);
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		if (!gp.getState().equals(GamePeriodState.TO_BE_LOTTERY)) {
			//跳转到中间界面 提示信息 并跳转到游戏首页
			logger.info("====================已停止投注===================");
			return buildModelView("redirect:/fgame/"+id+"/index", request);
		}
		if (CollectionUtils.isNotEmpty(context.getCathecticRepository().find_all_by_gameId_period_userId(period, id, user.getId(), MunualOrAuto.AUTO))) {
			//跳转到中间界面 提示信息 并跳转到游戏首页  已自动投注
			logger.info("====================已自动投注===================");
			return buildModelView("redirect:/fgame/"+id+"/index", request);
		}
		List<Odds> odds = context.getOddsRepository().find_all_by_game(id);
		List<CathecticModelDetail> details =context.getCathecticModelDetailRepository()
				.find_by_modelId(modelId==null?0:(modelId.matches("^\\d+$")?Long.parseLong(modelId):0));
		CathecticModel model = context.getCathecticModelRepository()
				.findOne(modelId==null?0:(modelId.matches("^\\d+$")?Long.parseLong(modelId):0));
		Object totalMoney = context.getCathecticRepository().sum_by_game_and_period(period, id);
		DecimalFormat df = new DecimalFormat("0.####");
		if(CollectionUtils.isEmpty(details)){//没有使用投注模式
			details = new ArrayList<CathecticModelDetail>();
			
			for(Odds odd:odds){
				CathecticModelDetail detail = new CathecticModelDetail();
				detail.setBetNumber(odd.getNumber());
				detail.setStandardRate(odd.getStandard());
				if (totalMoney == null) {
					detail.setCurrentRate(odd.getStandard());
				}else{
					Object number_totalMoney = 
							context.getCathecticRepository()
							.sum_by_game_and_period_and_betnumber(period, id, odd.getNumber());
					if (number_totalMoney == null) {
						detail.setCurrentRate(odd.getStandard());
					}else{
						detail.setCurrentRate(
								Double.parseDouble(df.format(
										Double.parseDouble(totalMoney.toString())/
										Double.parseDouble(number_totalMoney.toString()))));
					}
				}
				details.add(detail);
			}
		}else{//使用了投注模式
			for(Odds odd:odds){
				boolean flag = true;
				for(CathecticModelDetail detail:details){
					if(detail.getBetNumber() == odd.getNumber()){
						detail.setStandardRate(odd.getStandard());
						flag =false;
					}
				}
				if (flag) {
					CathecticModelDetail detail = new CathecticModelDetail();
					detail.setBetNumber(odd.getNumber());
					detail.setStandardRate(odd.getStandard());
					details.add(detail);
				}
			}
			Collections.sort(details, new Comparator<CathecticModelDetail>() {

				@Override
				public int compare(CathecticModelDetail o1, CathecticModelDetail o2) {
					return o1.getBetNumber()-o2.getBetNumber();
				}
			});
			//设置每一个号码的当前赔率
			for(CathecticModelDetail detail:details){
				if (totalMoney == null) {
					detail.setCurrentRate(detail.getStandardRate());
				}else{
					Object number_totalMoney = 
							context.getCathecticRepository()
							.sum_by_game_and_period_and_betnumber(period, id, detail.getBetNumber());
					if (number_totalMoney == null) {
						detail.setCurrentRate(detail.getStandardRate());
					}else{
						detail.setCurrentRate(
								Double.parseDouble(df.format(
										Double.parseDouble(totalMoney.toString())/
										Double.parseDouble(number_totalMoney.toString()))));
					}
				}
			}
		}
		DateFormat dfFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return buildModelView("/game/manualbet", request)
				.add("details", details)
				.add("models", context.getCathecticModelRepository().find_all_by_game_user(id, user.getId()))
				.add("model", model)
				.add("period",period)
				.add("serverTime",dfFormat.format(new Date()))
				.add("lotteryTime", dfFormat.format(gp.getLotteryTime()));
	}
	
	/**
	 * 保存手工投注
	 * @param request
	 * @param id
	 * @param period
	 * @param detail_json
	 * @return
	 */
	@RequestMapping(value="{id}/savemanual",method=RequestMethod.POST)
	public MallModelView savemanual(HttpServletRequest request,@PathVariable long id,
			long period,String detail_json,long total_money){
		GamePeriod gp = context.getGamePeriodRepository().find_by_gameId_and_period(id, period).get(0);
		if (!gp.getState().equals(GamePeriodState.TO_BE_LOTTERY)) {
			//跳转到中间界面 提示信息 并跳转到游戏首页  已结束投注
			logger.info("====================已停止投注===================");
			return buildModelView("redirect:/fgame/"+id+"/index", request);
		}
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		if (user.getCoin() < total_money) {
			//跳转到中间界面 提示信息 并跳转到游戏首页  金币不足
			logger.info("====================金币不足===================");
			return buildModelView("redirect:/fgame/"+id+"/index", request);
		}
		if (CollectionUtils.isNotEmpty(context.getCathecticRepository().find_all_by_gameId_period_userId(period, id, user.getId(), MunualOrAuto.AUTO))) {
			//跳转到中间界面 提示信息 并跳转到游戏首页  已自动投注
			logger.info("====================已自动投注===================");
			return buildModelView("redirect:/fgame/"+id+"/index", request);
		}
		
		//保存投注记录、  添加资金明细  、修改奖池总数 、投注人数、  修改用户金币 
		Game game = context.getGameRepository().findOne(id);
		JSONArray array = JSONArray.fromObject(detail_json);
		if (array.size()>0) {
			long userCoin = user.getCoin();
			for (Object object : array) {
				Cathectic c = (Cathectic) JSONObject.toBean(JSONObject.fromObject(object),Cathectic.class);
				c.setGameId(id);
				c.setGamePeriod(period);
				c.setUserId(user.getId());
				c.setMunualOrAuto(MunualOrAuto.MUNUAL);
				context.getCathecticRepository().save(c);
				context.getDetailsOfFundsRepository().save(new DetailsOfFunds(
						user.getId(), DetailType.MANUAL_BET, userCoin,userCoin-c.getBetMoney(),
						-c.getBetMoney(), game.getName(),period,c.getBetNumber()));
				userCoin = userCoin-c.getBetMoney();
			}
			context.getUserRepository().update_user_coin_for_bet_money(user.getId(), total_money);
			context.getGamePeriodRepository().update_bet_user_numbers(id, period, 1);
			context.getGamePeriodRepository().update_total_money(id, period, total_money);
		}
		
		return buildModelView("redirect:/fgame/"+id+"/index", request);
	}
	
	/**
	 * 点击已开奖
	 * @param request
	 * @param id
	 * @param period
	 * @return
	 */
	@RequestMapping("{id}/lotteryResult")
	public MallModelView lotteryResult(HttpServletRequest request,@PathVariable long id,long period){
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		List<Odds> oddList = context.getOddsRepository().find_all_by_game(id);
		Object totalMoney = context.getCathecticRepository().sum_by_game_and_period(period, id);
		DecimalFormat df = new DecimalFormat("0.####");
		for (Odds odds : oddList) {
			//设置 投注数量和获得数量
			List<Object[]> arrObjects  = context.getCathecticRepository().find_bet_money_by_game_period_user_bet_number(period, id, user.getId(), odds.getNumber());
			if (arrObjects != null && arrObjects.size()>0) {
				odds.setBetmoney(Long.parseLong(arrObjects.get(0)[0].toString()));
				odds.setWinmoney(Long.parseLong(arrObjects.get(0)[1].toString()));
			}
			//设置当前赔率
			if (totalMoney == null) {
				odds.setCurrentRate(odds.getStandard());
			}else{
				Object number_totalMoney = 
						context.getCathecticRepository()
						.sum_by_game_and_period_and_betnumber(period, id, odds.getNumber());
				if (number_totalMoney == null) {
					odds.setCurrentRate(odds.getStandard());
				}else{
					odds.setCurrentRate(
							Double.parseDouble(df.format(
									Double.parseDouble(totalMoney.toString())/
									Double.parseDouble(number_totalMoney.toString()))));
				}
			}
		}
		
		return buildModelView("/game/lotteryresult", request)
				.add("period", period)
				.add("oddList",oddList);
	}
	
	/**
	 * 点击中奖人数
	 * @param request
	 * @param id
	 * @param period
	 * @return
	 */
	@RequestMapping("{id}/lotteryUsers")
	public MallModelView lotteryUsers(@PageableDefault(page=0,size=40) Pageable pageable ,
			HttpServletRequest request,@PathVariable long id,long period){
		
		return buildModelView("/game/winners", request)
				.add("period",period)
				.add("records",context.getWinnerRecordRepository().find_all_by_game_period(id, period, pageable));
	}
	
	/**
	 * 走势图
	 * @param request
	 * @param id
	 * @param num 稍后设置下num为String
	 * @return
	 */
	@RequestMapping(value="{id}/trendchart",method={RequestMethod.GET,RequestMethod.POST})
	public MallModelView trendchart(HttpServletRequest request,@PathVariable long id,String num){
		
		if (num==null) {
			num="100";
		}
		if (!num.matches("^\\d+$")) {
			num="100";
		}
		long search_num = Long.parseLong(num);
		
		if (search_num > 2000) {
			search_num = 2000;
		}
		
		List<String> headRight = new ArrayList<String>();
		headRight.add("单");headRight.add("双");
		headRight.add("大");headRight.add("小");
		headRight.add("中");headRight.add("边");
		headRight.add("大尾");headRight.add("小尾");
		headRight.add("/3");headRight.add("/4");headRight.add("/5");
		headRight.add("开奖时间");
		List<Integer> headRightTimes = new ArrayList<Integer>();
		for(int i= 0;i<12;i++){
			headRightTimes.add(0);
		}
		
		List<Odds> odds = context.getOddsRepository().find_all_by_game(id);
		List<Integer> realInterval = new ArrayList<Integer>();
		List<Integer> realTimes =new ArrayList<Integer>();
		for (int i = 0; i < odds.size(); i++) {
			realInterval.add(Integer.valueOf(num+"")-1);
			realTimes.add(0);
		}
		
		AbstractPageRequest pageRequest = new AbstractPageRequest(0,Integer.valueOf(search_num+"")) {
			private static final long serialVersionUID = 1L;
			@Override
			public Sort getSort() {
				return null;
			}
			@Override
			public Pageable previous() {
				return null;
			}
			@Override
			public Pageable next() {
				return null;
			}
			@Override
			public Pageable first() {
				return null;
			}
		};
		
		Page<GamePeriod> periods = context.getGamePeriodRepository()
						.find_all_lotteryed_by_gameId(id, pageRequest);
		//确定大小  中边 边界
		int big_litter_line = odds.get(odds.size()-1).getNumber()/2;//小于等于这个的 为小
		int weiba_line = 9/2;
		int low_side = 9;
		int super_side = 18;
		if (id==3) {
			low_side = 7;
			super_side =14;
		}else if (id ==2) {
			low_side = 4;
			super_side = 10;
		}else if (id == 4) {
			low_side = 3;
			super_side = 8;
		}
		if (periods.getTotalElements()>0) {
			for (int i = 0; i < periods.getNumberOfElements(); i++) {
				GamePeriod gp = periods.getContent().get(i);
				for (int j=0;j<odds.size();j++) {
					
					if (gp.getResultNumber() == odds.get(j).getNumber()) {
						if (i<realInterval.get(j)) {
							realInterval.set(j, i);
						}
						realTimes.set(j, realTimes.get(j)+1);
						break;
					}
				}
				int temp = gp.getResultNumber();
				//设置单双
				if (temp%2!=0) {
					headRightTimes.set(0, headRightTimes.get(0)+1);
					gp.setEven(false);
				}else {
					headRightTimes.set(1, headRightTimes.get(1)+1);
					gp.setEven(true);
				}
				if (temp> big_litter_line) {
					headRightTimes.set(2, headRightTimes.get(2)+1);
					gp.setBig(true);
				}else {
					headRightTimes.set(3, headRightTimes.get(3)+1);
					gp.setBig(false);
				}
				if (temp>low_side && temp<super_side) {
					headRightTimes.set(4, headRightTimes.get(4)+1);
					gp.setSide(false);
				}else {
					headRightTimes.set(5, headRightTimes.get(5)+1);
					gp.setSide(true);
				}
				if ((temp%10)>weiba_line) {
					headRightTimes.set(6, headRightTimes.get(6)+1);
					gp.setBig_tail(true);
				}else {
					headRightTimes.set(7, headRightTimes.get(7)+1);
					gp.setBig_tail(false);
				}
			}
		}
		GamePeriod period = context.getGamePeriodRepository()
				.find_to_be_lottery_by_gameId_state(id).get(0);
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return buildModelView("/game/trendchart", request)
				.add("num", num).add("headRight", headRight)
				.add("headRightTimes", headRightTimes)
				.add("periods",periods)
				.add("realTimes", realTimes)
				.add("realInterval", realInterval)
				.add("period", period.getPeriod())
				.add("to_be_lottery_time", df.format(period.getLotteryTime()))
				.add("serverTime",df.format(new Date()))
				.add("odds", odds)
				.add("low_side", low_side)
				.add("super_side", super_side)
				.add("weiba_line",weiba_line);
	}
	
	/**
	 * 赢利统计
	 * 
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("{id}/profit")
	public MallModelView profit(HttpServletRequest request,@PathVariable long id){
		Calendar start = Calendar.getInstance();
		start.set(start.get(Calendar.YEAR), start.get(Calendar.MONTH),start.get(Calendar.DAY_OF_MONTH),
				0,0,0);
		Calendar end = Calendar.getInstance();
		end.set(end.get(Calendar.YEAR), end.get(Calendar.MONTH),end.get(Calendar.DAY_OF_MONTH),
				23,59,59);
		
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		List<List<String>> money_statictis = new ArrayList<List<String>>();
		List<List<String>> period_winning_statictis = new ArrayList<List<String>>();
		List<Game> games = context.getGameRepository().findAll();
		
		
		for (Game game : games) {
			List<String> tempList = new ArrayList<String>();
			tempList.add(game.getName());
			long temp_total = 0;
			
			List<String> tempList2 = new ArrayList<String>();
			long temp_total2 = 0;
			double winning2 = 0;
			tempList2.add(game.getName());
			for (int i = 1; i < 9; i++) {
				Long temp = context.getCathecticRepository()
						.sum_by_game_user_someday(game.getId(), user.getId(), start.getTime(), end.getTime());
				if (temp == null) {
					tempList.add(0+"");
				}else {
					tempList.add(temp+"");
					temp_total += temp;
				}
				
				Long temp_period = context.getCathecticRepository()
						.count_period_by_game_user_someday(game.getId(), user.getId(), start.getTime(), end.getTime());
				Long temp_win_period = context.getCathecticRepository()
						.count_win_period_by_game_user_someday(game.getId(), user.getId(), start.getTime(), end.getTime());
				if (temp_period == null) {
					tempList2.add("0期,0%");
				}else {
					if (temp_win_period == null||temp_win_period ==0) {
						tempList2.add(temp_period+"期,0%");
					}else {
						winning2 += (temp_win_period/temp_period);
						tempList2.add(temp_period+"期,"+(100*temp_win_period/temp_period)+"%");
					}
					temp_total2 += temp_period;
				}
				
				
				start.add(Calendar.DAY_OF_MONTH, -1);
				end.add(Calendar.DAY_OF_MONTH, -1);
			}
			tempList.add(temp_total+"");
			money_statictis.add(tempList);
			
			tempList2.add(temp_total2+"期,"+(100*winning2)+"%");
			period_winning_statictis.add(tempList2);
			start.add(Calendar.DAY_OF_MONTH, 8);
			end.add(Calendar.DAY_OF_MONTH, 8);
		}
		
		for (int i = 0; i < 1; i++) {
			List<String> tempList = new ArrayList<String>();
			tempList.add("总和");
			long temp_total = 0;
			
			List<String> tempList2 = new ArrayList<String>();
			tempList2.add("总和");
			long temp_total2 = 0;
			double winning2 = 0;
			for (int j = 1; j < 9; j++) {
				Long temp = context.getCathecticRepository()
						.sum_by_user_someday( user.getId(), start.getTime(), end.getTime());
				if (temp == null) {
					tempList.add(0+"");
				}else {
					tempList.add(temp+"");
					temp_total += temp;
				}
				
				Long temp_period = context.getCathecticRepository()
						.count_period_by_user_someday( user.getId(), start.getTime(), end.getTime());
				Long temp_win_period = context.getCathecticRepository()
						.count_win_period_by_user_someday( user.getId(), start.getTime(), end.getTime());
				if (temp_period == null) {
					tempList2.add("0期,0%");
				}else {
					if (temp_win_period == null ||temp_win_period ==0) {
						tempList2.add(temp_period+"期,0%");
					}else {
						winning2 += (temp_win_period/temp_period);
						tempList2.add(temp_period+"期,"+(100*temp_win_period/temp_period)+"%");
					}
					temp_total2 += temp_period;
				}
				
				start.add(Calendar.DAY_OF_MONTH, -1);
				end.add(Calendar.DAY_OF_MONTH, -1);
			}
			tempList.add(temp_total+"");
			money_statictis.add(tempList);
			
			tempList2.add(temp_total2+"期,"+(100*winning2)+"%");
			period_winning_statictis.add(tempList2);
			
			start.add(Calendar.DAY_OF_MONTH, 8);
			end.add(Calendar.DAY_OF_MONTH, 8);
		}
		//构造表头
		DateFormat df = new SimpleDateFormat("MM月dd日");
		List<String> tablehead = new ArrayList<String>();
		tablehead.add("游戏");
		for(int i=0;i<8;i++){
			tablehead.add(df.format(start.getTime()));
			start.add(Calendar.DAY_OF_MONTH, -1);
		}
		tablehead.add("总和");
		
		return buildModelView("/game/profit", request)
				.add("tablehead", tablehead)
				.add("money_statictis", money_statictis)
				.add("period_winning_statictis", period_winning_statictis);
	}
	
	/**
	 * 查看我的投注
	 * @param request
	 * @param id 游戏类型ID
	 * @param type 查看方式 1投注总和 2 手工投注 3挂机总和 4 单个方案  如果为null默认为1 投注总和
	 * @param auto 如果是单个方案的查看方式，代表选择的自动投注 类型+自动投注ID
	 * @param date 日期 如果为null默认今天
	 * @param upOrdown 向上或者向下翻日期
	 * @return
	 * 思路：
	 * 根据条件从投注表中找出符合条件的gamepriodId
	 * 根据找到的id找出所有的gamePeriod
	 * 设置每个gamePeriod的 用户投注  用户中奖  用户赢利  用户盈亏比例
	 * @throws ParseException 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="{id}/selfbet",method={RequestMethod.GET,RequestMethod.POST})
	public MallModelView selfbet(@PageableDefault(page=0,size=40)Pageable pageable,HttpServletRequest request,
			@PathVariable long id,String type,String auto,String date,String upOrdown,String viewState) throws ParseException, UnsupportedEncodingException{
		if(viewState!=null && !viewState.equals("")){
			String[] temp = new String(Base64.getUrlDecoder().decode(viewState),"utf-8").split(":");
			type=temp[0];
			auto=(temp[1].equals("")?null:temp[1]);
			date=temp[2];
		}
		Calendar start = Calendar.getInstance();
		Calendar end = Calendar.getInstance();
		User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
		DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
		if (date!=null && !date.equals("")) {//应使用reg判断
			start.setTime(df.parse(date));
			end.setTime(df.parse(date));
			if (upOrdown!=null && upOrdown.equals("up")) {
				start.set(start.get(Calendar.YEAR), start.get(Calendar.MONTH),start.get(Calendar.DAY_OF_MONTH),
						0,0,0);
				Calendar tempCalendar = Calendar.getInstance();
				tempCalendar.set(start.get(Calendar.YEAR), start.get(Calendar.MONTH),start.get(Calendar.DAY_OF_MONTH),
						0,0,0);
				if (start.compareTo(tempCalendar)<0) {
					start.add(Calendar.DAY_OF_MONTH, 1);
					end.add(Calendar.DAY_OF_MONTH, 1);
				}
			}
			if (upOrdown!=null && upOrdown.equals("down")) {
				start.add(Calendar.DAY_OF_MONTH, -1);
				end.add(Calendar.DAY_OF_MONTH, -1);
			}
		}
		date = df.format(start.getTime());
		
		start.set(start.get(Calendar.YEAR), start.get(Calendar.MONTH),start.get(Calendar.DAY_OF_MONTH),
				0,0,0);
		end.set(end.get(Calendar.YEAR), end.get(Calendar.MONTH),end.get(Calendar.DAY_OF_MONTH),
				23,59,59);
		
		if (type==null) {
			type="1";
		}
		viewState = Base64.getUrlEncoder().encodeToString((type+":"+((auto!=null&&!auto.equals(""))?auto:"")+":"+date).getBytes("utf-8"));
		List<Long> period_ids = new ArrayList<Long>();
		if (type.equals("1")) {//总和
			period_ids = context.getCathecticRepository()
					.find_period_by_game_user_someday(id, user.getId(), start.getTime(), end.getTime());
		}else if (type.equals("2")) {//手工
			period_ids = context.getCathecticRepository()
					.find_period_by_game_user_moa_someday(id, user.getId(),
							start.getTime(), end.getTime(), MunualOrAuto.MUNUAL);
		}else if (type.equals("3")) {//挂机
			period_ids = context.getCathecticRepository()
					.find_period_by_game_user_moa_someday(id, user.getId(),
							start.getTime(), end.getTime(), MunualOrAuto.AUTO);
		}else if (type.equals("4")) {//某个挂机方案
			if (auto!=null && !auto.equals("")) {//auto格式 类型名称:自动投注id 例如 AUTO_BET,1
				String[] arr = auto.split(",");
				period_ids = context.getCathecticRepository()
						.find_period_by_game_user_betType_betId_someday(
								id, user.getId(), start.getTime(), end.getTime(),
								AutoBetType.valueOf(arr[0]), Long.valueOf(arr[1]));
			}
		}
		
		if (period_ids.size() == 0) {
			period_ids.add(0l);
		}
		Page<GamePeriod> periods = context.getGamePeriodRepository().find_by_game_periods(period_ids, id, pageable);
		long total=0;
		long profit = 0;
		double win_rate = 0;
		
		if (periods != null) {
			total = periods.getTotalElements();
			long temp_win = 0;
			for (GamePeriod gamePeriod : periods) {
				Long sum = context.getCathecticRepository()
						.sum_by_game_period_user(id, user.getId(), gamePeriod.getPeriod());
				Long sum_winning = context.getCathecticRepository()
						.sum_winning_by_game_period_user(id, user.getId(), gamePeriod.getPeriod());
				if (sum != null) {
					gamePeriod.setSingleUserBetMoney(sum);
				}
				if(sum_winning != null){
					gamePeriod.setSingleUserWinMoney(sum_winning);
					temp_win +=1;
				}
				long temp_profit = gamePeriod.getSingleUserWinMoney()-gamePeriod.getSingleUserBetMoney();
				gamePeriod.setProfit(temp_profit);
				profit += temp_profit;
				//盈亏比例未设置
			}
			if (total>0) {
				win_rate = 100*temp_win/total;
			}
		}
		return buildModelView("/game/selfbet", request)
				.add("type", type)
				.add("auto", auto)
				.add("date", date)
				.add("viewState", viewState)
				.add("periods", periods)
				.add("total", total)
				.add("profit", profit)
				.add("win_rate", win_rate)
				.add("autobets", context.getAutoBetRepository().find_by_game_user(id, user.getId()))
				.add("permutationbets", context.getPermutationBetRepository().find_by_game_user(id, user.getId()));
	}
	
}
